package com.ruoyi.common.websocket.handler;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

// WebSocket 处理器
@Component
@Slf4j
public class NotificationWebSocketHandler extends TextWebSocketHandler {
    
    // 存储所有连接的客户端
    private static final Set<WebSocketSession> sessions = ConcurrentHashMap.newKeySet();
    
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
        log.info("新的WebSocket连接建立: {}" , session.getId());
        
        // 发送欢迎消息
        JsonObject welcomeMessage = new JsonObject();
        welcomeMessage.addProperty("type", "welcome");
        welcomeMessage.addProperty("content", "连接成功");
        session.sendMessage(new TextMessage(welcomeMessage.toString()));
    }
    
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        log.info("收到消息: " + payload);

        try {
            // 解析JSON消息
            JsonObject jsonObject = JsonParser.parseString(payload).getAsJsonObject();

            // 正确获取type字段，避免爆红
            if (jsonObject.has("type")) {
                String type = jsonObject.get("type").getAsString();
                log.info("消息类型: {}", type);

                // 如果是identification类型消息
                if ("identification".equals(type)) {
                    String clientId = jsonObject.get("clientId").getAsString();
                    // 添加这一行来显示clientId
                    log.info("WebSocket客户端标识: {}", clientId);

                    // 其他处理逻辑...
                }
            }
        } catch (Exception e) {
            log.error("解析消息失败: " + e.getMessage());
        }
    }


    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessions.remove(session);
        log.info("WebSocket连接关闭: " + session.getId());
    }
    
    // 向所有客户端发送消息
    public static void broadcastMessage(String message) {
        log.info("当前共有客户端数：{}: " , sessions.size());
        sessions.forEach(session -> {
            try {
                if (session.isOpen()) {
                    log.info("发送消息给客户端: " + session.getId());
                    session.sendMessage(new TextMessage(message));
                }
            } catch (Exception e) {
                log.error("发送消息失败: " + e.getMessage());
            }
        });
    }
    
    // 向特定客户端发送消息
    public static void sendMessageToSession(WebSocketSession session, String message) {
        try {
            if (session.isOpen()) {
                session.sendMessage(new TextMessage(message));
            }
        } catch (Exception e) {
            log.error("发送消息失败: " + e.getMessage());
        }
    }
}